package club.janna.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;

import java.util.Arrays;

public class ZeroCopyDemo {

    /**
     * 将byte数组封装成ByteBuf
     */
    static void test1() {
        byte[] arr = {1, 2, 3, 4, 5};
        ByteBuf byteBuf = Unpooled.wrappedBuffer(arr);
        System.out.println("buf -> " + byteBuf);
        System.out.println("get 3 -> " + byteBuf.getByte(3));
        arr[3] = 0;
        System.out.println("get 3 -> " + byteBuf.getByte(3));

        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        System.out.println(Arrays.toString(bytes));
    }

    /**
     * 将多个ByteBuf在逻辑上合并成一个ByteBuf
     */
    static void test2() {
        ByteBuf byteBuf1 = Unpooled.wrappedBuffer(new byte[]{1, 2, 3, 4, 5});
        ByteBuf byteBuf2 = Unpooled.wrappedBuffer(new byte[]{6, 7, 8, 9, 0});
        CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
        compositeByteBuf.addComponents(true, byteBuf1, byteBuf2);
        System.out.println("composite byte buf -> " + compositeByteBuf);
        byte[] bytes = new byte[compositeByteBuf.readableBytes()];
        compositeByteBuf.readBytes(bytes);
        System.out.println(Arrays.toString(bytes));
        System.out.println("composite byte buf -> " + compositeByteBuf);
    }

    /**
     * 将ByteBuf分割成多个ByteBuf，新的ByteBuf中会保留原ByteBuf的信息
     */
    static void test3() {
        ByteBuf byteBuf = Unpooled.buffer(10);
        for (int i = 0; i < 10; i++) {
            byteBuf.writeByte(i);
        }
        System.out.println("byteBuf -> " + byteBuf);
        System.out.println("read byte buf -> " + byteBuf.readByte());
        System.out.println("read byte buf -> " + byteBuf.readByte());
        ByteBuf nByteBuf = byteBuf.slice();
        System.out.println("new byte buf -> " + nByteBuf);
        System.out.println("read byte buf -> " + byteBuf.readByte());
        System.out.println("read byte buf -> " + byteBuf.readByte());
        System.out.println("new byte buf -> " + nByteBuf);
        System.out.println("read new byte buf -> " + nByteBuf.readByte());
        System.out.println("read new byte buf -> " + nByteBuf.readByte());
        System.out.println("new byte buf -> " + nByteBuf);
    }

    public static void main(String[] args) {
        System.out.println("----------------- test1 ----------------------");
        test1();
        System.out.println("\r\n\r\n----------------- test2 ----------------------");
        test2();
        System.out.println("\r\n\r\n----------------- test3 ----------------------");
        test3();
    }
}
